#define BTN_UP 1
#define BTN_DOWN 0

#define PIN_SPEED_UP   12
#define PIN_SPEED_DOWN 11
#define SPEED_INCREAMENT 0.2


enum SpeedAction {
  SPEED_UP, SPEED_DOWN, SPEED_STAY, SPEED_CONFIRM
};


// ====== global variables ======
float g_tar_speed = 0;  // target speed
SpeedAction g_action = SPEED_STAY;


bool TimeUp() {
  static unsigned long _this_time, _last_time;
  _this_time = millis();
  if (_this_time - _last_time > 200) {
    _last_time = _this_time;
    return true;
  }
  return false;
}


void ReadButton() {
  int lev_up  = digitalRead(PIN_SPEED_UP);
  int lev_down = digitalRead(PIN_SPEED_DOWN);

  if (BTN_UP == lev_up && BTN_UP == lev_down) {
    g_action = SPEED_STAY;
  }
  else if (BTN_DOWN == lev_up && BTN_UP == lev_down) {
    g_action = SPEED_UP;
  }
  else if(BTN_UP == lev_up && BTN_DOWN == lev_down) {
    g_action = SPEED_DOWN;
  }
  else {
    g_action = SPEED_CONFIRM;
  }
}


void PrintSpeed() {
//  Serial.print("act: "); Serial.print(g_action);
  Serial.print(" spd: "); Serial.println(g_tar_speed);
}


void DoAction() {
  if (TimeUp()) {
    switch (g_action) {
      case SPEED_UP:
        Serial.print("speed up "); PrintSpeed();
        g_tar_speed += SPEED_INCREAMENT; break;
      case SPEED_DOWN:
        Serial.print("speed down "); PrintSpeed();
        g_tar_speed -= SPEED_INCREAMENT; break;
      case SPEED_CONFIRM:
        Serial.print("confirm "); PrintSpeed();
    }
  }
}


void setup() {
  pinMode(PIN_SPEED_UP, INPUT_PULLUP);
  pinMode(PIN_SPEED_DOWN, INPUT_PULLUP);

  Serial.begin(57600);
}


void loop() {
  ReadButton();
  DoAction();
}
